package com.sys.midware.hive.pool;

import java.sql.Connection;
import java.util.Hashtable;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sys.midware.hive.config.BHiveConfig;
import com.sys.midware.hive.config.BHiveConfigMapHolder;
import com.sys.midware.hive.config.BHiveConfigUtil;


/**
 * 连接管理类
 *
 */
public class ConnectionPoolManager {

	private static final Logger logger = LoggerFactory.getLogger(ConnectionPoolManager.class);

	
	  // 初始化  
    private ConnectionPoolManager(){  
        init();  
    }  
    // 单例实现  
    public static ConnectionPoolManager getInstance(){  
        return Singtonle.instance;  
    }  
    private static class Singtonle {  
        private static ConnectionPoolManager instance =  new ConnectionPoolManager();  
    }  
	
	
	/**
	 * 连接池存放
	 */
	public Hashtable<String, IConnectionPool> pools = new Hashtable<String, IConnectionPool>();
	private boolean initialized = false;

	/**
	 * 初始化所有的连接池
	 */
	public synchronized void init() {
		logger.trace(" entered.");
		if(!initialized){
		    BHiveConfigUtil.initConfig();
		    Map<String, BHiveConfig> configMap = BHiveConfigMapHolder.get();
		    for (Map.Entry<String, BHiveConfig> entry : configMap.entrySet()) {
//		        System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
		        ConnectionPool pool = new ConnectionPool( entry.getValue());
	            pools.put(entry.getKey(), pool);
		    }
		}
		
		initialized = true;
	}

	/**
	 * 获得连接,根据连接池名字 获得连接
	 * @param poolName
	 * @return
	 */
	public Connection getConnection(String poolName) {
		logger.trace("getConnection(" + poolName + ")");
		if( !initialized ) init();
		Connection conn = getPool(poolName).getCurrentConnecton();
		if(null != conn){
			logger.info("根据连接池名字，获取connection连接 version:" + conn);
		} else {
			logger.error("根据连接池名字，获取connection连接失败 conn为空!");
		}
		return conn;
	}

	/**
	 * 关闭，回收连接
	 */
	public void close(String poolName, Connection conn) {
		logger.trace("Invoked");
		IConnectionPool pool = getPool(poolName);
		if (pool != null) {
			logger.info("开始关闭，回收连接");
			pool.releaseConnection(conn);
		} else {
			logger.info("回收连接时发现pool为空");
		}
	}

	/**
	 * 清空连接池
	 * @param poolName
	 */
	public void destroy(String poolName) {
		logger.trace("Invoked");
		IConnectionPool pool = getPool(poolName);
		if (pool != null) {
			pool.destroy();
		}
	}

	/**
	 * 获得连接池
	 * @param poolName
	 * @return
	 */
	public IConnectionPool getPool(String poolName) {
		logger.trace("Invoked");
		IConnectionPool pool = null;
		if (pools.size() > 0) {
			logger.info("pool【"+poolName+"】 size: "+pools.size());
			pool = pools.get(poolName);
			logger.trace("pool:" + pool);
		} else {
			logger.trace("pool size: 0");
		}
		return pool;
	}
}
